package com.quanshu.shop.main.view;

import android.content.Context;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.GridLayoutHelper;
import com.alibaba.android.vlayout.layout.SingleLayoutHelper;
import com.gyf.barlibrary.ImmersionBar;
import com.quanshu.exchange.R;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseObserver;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.base.BaseFragment;
import com.quanshu.exchange.ui.base.MyApplication;
import com.quanshu.exchange.ui.gui.login.LoginActivity;
import com.quanshu.shop.base.tool.BaseTool;
import com.quanshu.shop.goods.entity.MyCartEntity;
import com.quanshu.shop.goods.view.CartActivity;
import com.quanshu.shop.goods.view.SearchActivity;
import com.quanshu.shop.main.adapter.BannerAdapter;
import com.quanshu.shop.main.adapter.HotGoodsAdapter;
import com.quanshu.shop.main.adapter.LikeGoodsAdapter;
import com.quanshu.shop.main.adapter.NineGridAdapter;
import com.quanshu.shop.main.adapter.RecommendGoodsAdapter;
import com.quanshu.shop.main.adapter.Special1Adapter;
import com.quanshu.shop.main.adapter.SpecialAdapter;
import com.quanshu.shop.main.adapter.Title1Adapter;
import com.quanshu.shop.main.adapter.TitleAdapter;
import com.quanshu.shop.main.api.ShopMainIF;
import com.quanshu.shop.main.entity.ShopMainEntity;
import com.quanshu.shop.person.view.ShopPersonalActivity;
import com.quanshu.shop.sort.view.GoodsTypeActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link ShopMainFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ShopMainFragment extends BaseFragment {
    @BindView(R.id.shop_main_rlv)
    RecyclerView recyclerView;
    @BindView(R.id.shop_main_title)
    LinearLayout linearLayout;
    @BindView(R.id.shop_main_go_person)
    ImageView imageViewGo;
    @BindView(R.id.shop_main_sort)
    ImageView shopMainSort;
    @BindView(R.id.shop_main_cart)
    ImageView shopMainCart;
    @BindView(R.id.shop_main_cart_txt)
    TextView shopMainCartTxt;
    @BindView(R.id.shop_main_go_cart)
    ConstraintLayout shopMainGoCart;
    Unbinder unbinder;
    @BindView(R.id.shop_main_go_search)
    LinearLayout shopMainGoSearch;
    @BindView(R.id.shop_main_cart1)
    ImageView shopMainCart1;
    private Context mContext;
    private List<DelegateAdapter.Adapter> adapterList;
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public ShopMainFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ShopMainFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ShopMainFragment newInstance(String param1, String param2, Context context) {
        ShopMainFragment fragment = new ShopMainFragment();
        fragment.mContext = context;
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public int setFragmentLayoutID() {
        return R.layout.fragment_shop_main;
    }

    @Override
    public void onResume() {
        super.onResume();
        getCart();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ImmersionBar.with(this).destroy();
        unbinder.unbind();
    }

    private void init() {
        RxViewHelper.getInstance().clicks(shopMainGoSearch, aVoid ->
                BaseTool.goActivity(getActivity(), SearchActivity.class, null));
        VirtualLayoutManager virtualLayoutManager = new VirtualLayoutManager(mContext);
        DelegateAdapter delegateAdapter = new DelegateAdapter(virtualLayoutManager, false);
        recyclerView.setLayoutManager(virtualLayoutManager);
        RecyclerView.RecycledViewPool recycledViewPool = new RecyclerView.RecycledViewPool();
        recyclerView.setRecycledViewPool(recycledViewPool);
        recycledViewPool.setMaxRecycledViews(BannerAdapter.BANNER_TYPE, 10);
        recycledViewPool.setMaxRecycledViews(NineGridAdapter.NINE_GRID_TYPE, 10);
        recycledViewPool.setMaxRecycledViews(TitleAdapter.TITLE_TYPE, 2);
        recycledViewPool.setMaxRecycledViews(RecommendGoodsAdapter.RECOMMEND_GOODS_TYPE, 10);
        recycledViewPool.setMaxRecycledViews(SpecialAdapter.SPECIAL_TYPE, 10);
        recycledViewPool.setMaxRecycledViews(Special1Adapter.SPECIAL1_TYPE, 10);
        recycledViewPool.setMaxRecycledViews(HotGoodsAdapter.HOT_GOODS_TYPE, 10);
        recycledViewPool.setMaxRecycledViews(Title1Adapter.TITLE1_TYPE, 10);
        recycledViewPool.setMaxRecycledViews(LikeGoodsAdapter.LIKE_GOODS_TYPE, 10);
        NetClient.getInstance().getShopService(ShopMainIF.class)
                .getShopInfo("")
                .compose(new BaseTransformer<>((BaseActivity) getActivity()))
                .subscribe(new BaseObserver<BaseResponse<ShopMainEntity>>() {
                    @Override
                    public void onSuccess(BaseResponse<ShopMainEntity> response) {
                        //顶部banner
                        SingleLayoutHelper singleLayoutHelper = new SingleLayoutHelper();
                        singleLayoutHelper.setItemCount(1);
                        BannerAdapter bannerAdapter = new BannerAdapter(mContext, response.getData().getBanner(), singleLayoutHelper);
                        adapterList.add(bannerAdapter);
                        //九宫格视图
                        GridLayoutHelper gridLayoutHelper = new GridLayoutHelper(4);
                        gridLayoutHelper.setItemCount(response.getData().getClassify().size());
                        gridLayoutHelper.setPadding(20, 20, 20, 20);// 设置LayoutHelper的子元素相对LayoutHelper边缘的距离
                        gridLayoutHelper.setMargin(20, 20, 20, 20);// 设置LayoutHelper边缘相对父控件（即RecyclerView）的距离
//                        gridLayoutHelper.setBgColor(Color.GRAY);// 设置背景颜色
                        NineGridAdapter nineGridAdapter = new NineGridAdapter(mContext, response.getData().getClassify(), gridLayoutHelper);
                        adapterList.add(nineGridAdapter);
                        //今日推荐标题栏
                        SingleLayoutHelper singleLayoutHelper1 = new SingleLayoutHelper();
                        singleLayoutHelper1.setItemCount(1);
                        TitleAdapter titleAdapter = new TitleAdapter(mContext, "今日推荐", singleLayoutHelper1);
                        adapterList.add(titleAdapter);
                        //推荐商品
                        SingleLayoutHelper singleLayoutHelper2 = new SingleLayoutHelper();
                        singleLayoutHelper2.setItemCount(1);
                        List<ShopMainGoodsFragment> shopMainGoodsFragmentList = new ArrayList<>();
                        for (int a = 0; a < response.getData().getGoods().size(); a += 3) {
                            List<ShopMainEntity.GoodsEntity> goodsEntityList = new ArrayList<>();
                            if (response.getData().getGoods().size() - a >= 3) {
                                for (int b = a; b < a + 3; b++) {
                                    goodsEntityList.add(response.getData().getGoods().get(b));
                                }
                                ShopMainGoodsFragment shopMainGoodsFragment = ShopMainGoodsFragment.newInstance(mContext, goodsEntityList);
                                shopMainGoodsFragmentList.add(shopMainGoodsFragment);
                            } else {
                                if (response.getData().getGoods().size() - a > 0) {
                                    for (int b = a; b < response.getData().getGoods().size(); b++) {
                                        goodsEntityList.add(response.getData().getGoods().get(b));
                                    }
                                    ShopMainGoodsFragment shopMainGoodsFragment = ShopMainGoodsFragment.newInstance(mContext, goodsEntityList);
                                    shopMainGoodsFragmentList.add(shopMainGoodsFragment);
                                }

                            }


                        }
                        RecommendGoodsAdapter recommendGoodsAdapter = new RecommendGoodsAdapter(mContext, shopMainGoodsFragmentList, singleLayoutHelper2, getFragmentManager());
                        adapterList.add(recommendGoodsAdapter);
                        //特殊商品
                        SingleLayoutHelper singleLayoutHelper3 = new SingleLayoutHelper();
                        SpecialAdapter specialAdapter = new SpecialAdapter(mContext, response.getData().getSpecial(), singleLayoutHelper3);
                        adapterList.add(specialAdapter);
                        //特殊商品1
                        List<ShopMainEntity.SpecialEntity> specialEntityList = new ArrayList<>();
                        if (response.getData().getSpecial().size() >= 2) {
                            GridLayoutHelper gridLayoutHelper1 = new GridLayoutHelper(response.getData().getSpecial().size() - 1);
                            gridLayoutHelper1.setItemCount(response.getData().getSpecial().size() - 1);
                            for (int a = 1; a < response.getData().getSpecial().size(); a++) {
                                specialEntityList.add(response.getData().getSpecial().get(a));
                            }
                            Special1Adapter special1Adapter = new Special1Adapter(mContext, specialEntityList, gridLayoutHelper1);
                            adapterList.add(special1Adapter);
                        }

                        //标题2
                        SingleLayoutHelper singleLayoutHelper4 = new SingleLayoutHelper();
                        TitleAdapter titleAdapter1 = new TitleAdapter(mContext, "当季热销", singleLayoutHelper4);
                        adapterList.add(titleAdapter1);
                        //热销商品
                        GridLayoutHelper gridLayoutHelper2 = new GridLayoutHelper(2);
                        gridLayoutHelper2.setItemCount(response.getData().getHots().size());
//                        gridLayoutHelper2.setPadding(20, 20, 20, 20);// 设置LayoutHelper的子元素相对LayoutHelper边缘的距离
                        gridLayoutHelper2.setMargin(20, 20, 20, 20);
                        HotGoodsAdapter hotGoodsAdapter = new HotGoodsAdapter(mContext, response.getData().getHots(), gridLayoutHelper2);
                        adapterList.add(hotGoodsAdapter);
                        //标题3
                        SingleLayoutHelper singleLayoutHelper5 = new SingleLayoutHelper();
                        Title1Adapter title1Adapter = new Title1Adapter(mContext, "猜你喜欢", singleLayoutHelper5);
                        adapterList.add(title1Adapter);
                        //猜你喜欢商品
                        GridLayoutHelper gridLayoutHelper3 = new GridLayoutHelper(2);
                        gridLayoutHelper3.setItemCount(response.getData().getLikes().size());
                        gridLayoutHelper3.setBgColor(Color.parseColor("#f5f5f5"));
                        // gridLayoutHelper3.setPadding(30, 10, 30, 10);
                        LikeGoodsAdapter likeGoodsAdapter = new LikeGoodsAdapter(mContext, response.getData().getLikes(), gridLayoutHelper3);
                        adapterList.add(likeGoodsAdapter);
                        delegateAdapter.addAdapters(adapterList);
                        recyclerView.setAdapter(delegateAdapter);
                    }
                });


    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            ImmersionBar.with(this).statusBarDarkFont(true, 0.2f).statusBarColorTransform(R.color.white).titleBar(linearLayout).init();
        }
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {
        ImmersionBar.with(this).statusBarColor("#FFFFFF").statusBarDarkFont(true).titleBar(linearLayout).init();
        adapterList = new ArrayList<>();
        init();
        RxViewHelper.getInstance().clicks(imageViewGo, aVoid -> {
                    if (MyApplication.getInstance().getCurrentUser() == null) {
                        BaseTool.goActivity(mContext, LoginActivity.class, null);
                        return;
                    }
                    BaseTool.goActivity(getActivity(), ShopPersonalActivity.class, null);
                }
        );
        RxViewHelper.getInstance().clicks(shopMainSort, aVoid ->
                BaseTool.goActivity(mContext, GoodsTypeActivity.class, null)
        );
        RxViewHelper.getInstance().clicks(shopMainGoCart, aVoid ->
                BaseTool.goActivity(mContext, CartActivity.class, null)
        );

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    private void getCart() {
        //获取购物车列表
        if (MyApplication.getInstance().getCurrentUser() != null) {
            NetClient.getInstance().getShopService(ShopMainIF.class).getCartListInfo(AppUtils.getSignParams(MyApplication.getInstance().getCurrentUser().getId()), MyApplication.getInstance().getCurrentUser().getId())
                    .compose(new BaseTransformer<>((BaseActivity) mContext))
                    .subscribe(new BaseObserver<BaseResponse<MyCartEntity>>() {
                        @Override
                        public void onSuccess(BaseResponse<MyCartEntity> response) {
                            try {
                                shopMainCartTxt.setText(response.getData().getCount());
                                if (!TextUtils.isEmpty(response.getData().getCount())) {
                                    if (Integer.parseInt(response.getData().getCount()) > 0) {
                                        shopMainCart1.setVisibility(View.VISIBLE);
                                        shopMainCart.setVisibility(View.GONE);
                                    } else {
                                        shopMainCart1.setVisibility(View.GONE);
                                        shopMainCart.setVisibility(View.VISIBLE);
                                    }
                                }
                            } catch (Exception e) {

                            }

                        }
                    });
        }
    }


    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
